//
//  TagManager.m
//  Grammar
//
//  Created by Rick on 7/11/13.
//
//

#import "TagManager.h"
#import "Tag.h"
#import "ITTObjectSingleton.h"

#define TYTag @"TYTag"
#define TYTagArchiver @"TYTagArchiver"

@interface TagManager()
- (void)restore;
@end

@implementation TagManager
static TagManager *_sharedInst = nil;

+(TagManager*)sharedManager
{
    @synchronized(self) {
        if (_sharedInst == nil) {
            _sharedInst = [[self alloc] init];
        }
    }
    return _sharedInst;
}

-(id)init
{
    if ((self = [super init])) {
        [self restore];
    }
    return self;
}

- (void)saveData
{
    if (_tags) {
        NSMutableData *data = [[NSMutableData alloc] init];
        NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc]
                                     initForWritingWithMutableData:data];
        [archiver encodeObject:_tags forKey:TYTagArchiver];
        [archiver finishEncoding];
        [USER_DEFAULT setObject:data forKey:[NSString stringWithFormat:@"%@",TYTag] ];
        [archiver release];
        [data release];
        
        [USER_DEFAULT synchronize];
    }
}

- (void)readData
{
    NSData *data = [USER_DEFAULT objectForKey:[NSString stringWithFormat:@"%@",TYTag]];;
    if (!data) {
        return;
    }
    NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
    NSArray *array = [unarchiver decodeObjectForKey:TYTagArchiver];
    [unarchiver finishDecoding];
    [_tags addObjectsFromArray:array];
    [unarchiver release];
}

- (void)addTag:(Tag *)tag
{
    for (Tag *aTag in self.tags) {
        if ([aTag.tagId isEqualToString:tag.tagId]) {
            return;
        }
    }
    [_tags insertObject:tag atIndex:0];
    
    [self saveData];
}


- (void)updateTag:(Tag *)tag
{
    NSArray *array = [NSArray arrayWithArray:self.tags];
    for (Tag *aTag in array) {
        if ([aTag.tagId isEqualToString:tag.tagId]) {
            [_tags removeObject:aTag];
        }
    }
    [_tags insertObject:tag atIndex:0];
    
    [self saveData];
}

- (void)removeTag:(Tag *)tag
{
    NSArray *array = [NSArray arrayWithArray:self.tags];
    for (Tag *aTag in array) {
        if ([aTag.tagId isEqualToString:tag.tagId]) {
            [_tags removeObject:aTag];
            [self saveData];
        }
    }
}
- (Tag*)getTagWithid:(NSString*)tagId
{
    for (Tag *aTag in self.tags) {
        if ([aTag.tagId isEqualToString:tagId]) {
            return aTag;
        }
    }
    return nil;
}
- (NSMutableArray*)tags
{
    if (!_tags) {
        [self readData];
    }
    
    return _tags;
}

- (void)restore
{
    _tags = [[NSMutableArray alloc] init];
    [self readData];
}
- (void)dealloc
{
    [_tags release];
    [super dealloc];
}
- (void)clearMemoryData
{
    [_tags removeAllObjects];
}

- (void)removeAllTags
{
    [_tags removeAllObjects];
    [USER_DEFAULT removeObjectForKey:[NSString stringWithFormat:@"%@",TYTag]];
    [USER_DEFAULT synchronize];
}
@end
